<template>
	<view class="layout">
		<wd-navbar title="浙江弘晔包装材料有限公司"/>
		<wd-form ref="form" class="form" :model="formState">
			<wd-cell-group border>
				<wd-input label="用户名" prop="name" clearable v-model="formState.name"
					placeholder="请输入用户名" :rules="[{ required: true, message: '请填写用户名' }]" />
				<wd-input label="密码"  prop="password" show-password clearable
					v-model="formState.password" placeholder="请输入密码" :rules="[{ required: true, message: '请填写密码' }]" />
			</wd-cell-group>
			<view class="footer">
				<wd-button type="primary" size="large" @click="onSubmit" block>登录</wd-button>
			</view>
		</wd-form>
	</view>
</template>

<script setup lang="ts">
	import { LoginService } from '@/services';
	import { reactive, onMounted, onUnmounted } from 'vue';


	const formState = reactive({
		name: 'admin',
		password: 'admin123'
	});
	
	// PDA扫码处理函数
	const handlePDAScan = (code) => {
		console.log('登录页面接收到PDA扫码:', code);
		// 在登录页面，可以将扫码结果填入用户名或其他用途
		// 这里暂时只记录日志
	};
	
	onMounted(() => {
		// 监听PDA扫码
		uni.$on("urovo", handlePDAScan);
	});
	
	onUnmounted(() => {
		// 移除PDA扫码监听
		uni.$off("urovo", handlePDAScan);
	});
const onSubmit = async () => {
	// 显示加载状态
	uni.showLoading({
		title: '登录中...',
		mask: true
	});
	
	try {
		// 使用LoginService调用/login接口
		const result = await LoginService.loginPost({
			username: formState.name,
			password: formState.password
		});
		
		console.log('登录响应:', result);
		
		// 检查登录是否成功
		if (result && (result.token || result.Authorization)) {
			// 存储返回的token
			const token = result.token || result.Authorization;
			uni.setStorageSync("access-token", token);
			
			uni.hideLoading();
			uni.showToast({
				title: '登录成功',
				icon: 'success'
			});
			
			// 跳转到首页
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/index/index'
				});
			}, 1500);
		} else {
			uni.hideLoading();
			uni.showToast({
				title: '用户名或密码错误',
				icon: 'none'
			});
		}
	} catch (error) {
		uni.hideLoading();
		console.error('登录错误:', error);
		console.log('详细错误信息:', JSON.stringify(error, null, 2));
		
		// 显示详细错误信息
		let errorMsg = '网络错误';
		if (error && error.errMsg) {
			errorMsg = error.errMsg;
		} else if (error && error.message) {
			errorMsg = error.message;
		}
		
		uni.showToast({
			title: errorMsg.length > 20 ? '网络连接失败' : errorMsg,
			icon: 'none',
			duration: 3000
		});
	}
}
</script>

<style scoped>
	.layout {
		padding: 16rpx;
	}

</style>